import React, { useState } from 'react'
import { Form, Row, Col, Button, Space, Card } from 'antd'
import { DownOutlined, UpOutlined } from '@ant-design/icons'
import type { FormProps } from 'antd'

interface AdvancedSearchProps extends Omit<FormProps, 'onFinish'> {
  onSearch: (values: Record<string, any>) => void
  onReset?: () => void
  defaultCollapsed?: boolean
  children: React.ReactNode
}

const AdvancedSearch: React.FC<AdvancedSearchProps> = ({
  onSearch,
  onReset,
  defaultCollapsed = true,
  children,
  ...props
}) => {
  const [form] = Form.useForm()
  const [collapsed, setCollapsed] = useState(defaultCollapsed)

  const handleReset = () => {
    form.resetFields()
    onReset?.()
  }

  const handleSearch = async () => {
    const values = await form.validateFields()
    onSearch(values)
  }

  const childrenArray = React.Children.toArray(children)
  const showItems = collapsed ? childrenArray.slice(0, 3) : childrenArray

  return (
    <Card className="advanced-search">
      <Form
        form={form}
        {...props}
      >
        <Row gutter={24}>
          {showItems.map((item, index) => (
            <Col key={index} xs={24} sm={12} md={8} lg={6}>
              {item}
            </Col>
          ))}
        </Row>
        <Row>
          <Col span={24} style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={handleReset}>重置</Button>
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
              {childrenArray.length > 3 && (
                <Button
                  type="link"
                  onClick={() => setCollapsed(!collapsed)}
                >
                  {collapsed ? '展开' : '收起'}
                  {collapsed ? <DownOutlined /> : <UpOutlined />}
                </Button>
              )}
            </Space>
          </Col>
        </Row>
      </Form>
    </Card>
  )
}

export default AdvancedSearch 